package com.wn.ticket.web;

import com.wn.ticket.common.ResponseEntity;
import com.wn.ticket.entity.UserAddress;
import com.wn.ticket.mapper.UserAddressMapper;
import com.wn.ticket.service.UserAddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 地址管理
 *
 * @author 杜昭进
 * date: 2022/9/6
 */
@Slf4j
@RestController
@RequestMapping("/front/address")
public class AddressController {

    @Autowired
    private UserAddressService userAddressService;

    @RequestMapping("/add")
    public ResponseEntity add(@RequestBody UserAddress userAddress) {
        if (userAddress.getIsDefault() == null) {
            userAddress.setIsDefault("n");
        }
        if (userAddress.getDeleted() == null) {
            userAddress.setDeleted("n");
        }

        try {
            userAddressService.add(userAddress);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity("400","fail",e.getMessage());
        }
        return ResponseEntity.success;
    }

    @RequestMapping("/update")
    public ResponseEntity update(@RequestBody UserAddress userAddress) {
        log.debug("----------userAddress:{}",userAddress);
        try {
            userAddressService.update(userAddress);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity("400","fail",e.getMessage());
        }
        return ResponseEntity.success;
    }

    @RequestMapping("/del")
    public ResponseEntity del(@RequestBody UserAddress userAddress) {
        try {
            userAddressService.delete(userAddress);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity("400","fail",e.getMessage());
        }
        return ResponseEntity.success;
    }

    @RequestMapping("/list")
    public ResponseEntity list(@RequestBody UserAddress userAddress) {
        List<UserAddress> userAddresses=userAddressService.seleteByUserId(userAddress.getUser().getId());
        return new ResponseEntity(userAddresses);
    }

    @Autowired
    private UserAddressMapper userAddressMapper;
    @RequestMapping("/getDefault/{id}")
    public ResponseEntity getDefault(@PathVariable int id) {
        UserAddress userAddress = userAddressMapper.getDefaultByUserId(id);
        return new ResponseEntity(userAddress);
    }
}
